package org.jingouzhui.domain.strategy.service.armory;

import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.jingouzhui.domain.strategy.model.entity.StrategyAwardEntity;
import org.jingouzhui.domain.strategy.model.entity.StrategyEntity;
import org.jingouzhui.domain.strategy.model.entity.StrategyRuleEntity;
import org.jingouzhui.domain.strategy.repository.IStrategyRepository;
import org.jingouzhui.types.common.Delimiter;
import org.jingouzhui.types.exception.AppException;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.security.SecureRandom;
import java.util.*;

import static org.jingouzhui.types.common.Constants.RedisKey.STRATEGY_AWARD_STOCK_KEY;
import static org.jingouzhui.types.enums.ResponseCode.STRATEGY_RULE_WEIGHT_IS_NULL;

/**
 * @description: 策略装配库实现类
 * @author: jingouzhui
 * @date: 2025/4/24 14:32
 */
@Slf4j
@Service
public class StrategyArmoryDispatch implements IStrategyArmory,IStrategyDispatch {

    @Resource
    private IStrategyRepository strategyRepository;

    //现在是把所有的strategyId对应的awardId都查询出来的，但实际上还有rule的影响，
    //比如黑名单规则，权重规则等，所以需要根据查询出来的strategyAwardList和strategy中的ruleModel再过滤一下
    @Override
    public boolean assembleLotteryStrategy(Long strategyId) {
        log.info("开始策略装配, strategyId={}", strategyId);
        //1.查询策略配置
        List<StrategyAwardEntity> strategyAwardEntities = strategyRepository.queryStrategyAwardList(strategyId);
        if (strategyAwardEntities == null || strategyAwardEntities.isEmpty()) {
            log.error("strategyAwardEntities为空,strategyId={}", strategyId);
            return false;
        }
        //2.缓存奖品库存
        for (StrategyAwardEntity strategyAwardEntity : strategyAwardEntities) {
            Integer awardId = strategyAwardEntity.getAwardId();
            Integer  awardCountSurplus = strategyAwardEntity.getAwardCountSurplus();
            cacheStrategyAwardCount(strategyId,awardId,awardCountSurplus);
        }
        assembleLotteryStrategy(String.valueOf(strategyId),strategyAwardEntities);

        //3.权重策略配置 - 适用于 rule_weight 权重规则设置
        StrategyEntity strategy = strategyRepository.queryStrategyByStrategyId(strategyId);
        if(null == strategy || strategy.getRuleWeight() == null) {
            return true;
        }
        //4.获取策略规则
        StrategyRuleEntity strategyRuleEntity = strategyRepository.queryStrategyRule(strategyId,strategy.getRuleWeight());
        if (null == strategyRuleEntity) {
            log.error("对象不存在:{}", JSON.toJSONString(strategyRuleEntity));
            throw  new AppException(STRATEGY_RULE_WEIGHT_IS_NULL.getCode(),STRATEGY_RULE_WEIGHT_IS_NULL.getInfo());
        }
        Map<String, List<Integer>> ruleWeightValuesMap = strategyRuleEntity.getRuleWeightValues();
        Set<String> keys = ruleWeightValuesMap.keySet();
        for (String key : keys) {
            List<Integer> ruleWeightValues = ruleWeightValuesMap.get(key);
            List<StrategyAwardEntity> strategyAwardEntitiesClone = new ArrayList<>(strategyAwardEntities);
            strategyAwardEntitiesClone.removeIf(e -> ! ruleWeightValues.contains(e.getAwardId()));
            assembleLotteryStrategy(String.valueOf(strategyId).concat("_").concat(key),strategyAwardEntitiesClone);
        }

        return true;
    }

    private void assembleLotteryStrategy(String key, List<StrategyAwardEntity> strategyAwardEntities) {
        log.info("开始初始化查找表, key={}", key);
        //1.获取最小的概率值
        BigDecimal minAwardRate = strategyAwardEntities.stream()
                .map(StrategyAwardEntity::getAwardRate)
                .min(BigDecimal::compareTo)
                .orElse(BigDecimal.ZERO);

        //2.获取该策略下的概率总和
        BigDecimal totalAwardRate = strategyAwardEntities.stream()
                .map(StrategyAwardEntity::getAwardRate)
                .reduce(BigDecimal.ZERO, BigDecimal::add);

        //3.计算出概率范围
        BigDecimal totalRange = totalAwardRate.divide(minAwardRate,RoundingMode.CEILING);

        //4.计算出每个奖品占用的查找表的大小
        List<Integer> strategyAwardSearchRateTables = new ArrayList<>(totalRange.intValue());
        for (StrategyAwardEntity strategyAward : strategyAwardEntities) {
            Integer awardId = strategyAward.getAwardId();
            BigDecimal awardRate = strategyAward.getAwardRate();
            for (int i = 0; i < totalRange.multiply(awardRate).setScale(0, RoundingMode.CEILING).intValue(); i++) {
                strategyAwardSearchRateTables.add(awardId);
            }
        }

        //5.将查找表乱序
        Collections.shuffle(strategyAwardSearchRateTables);
        //6.加入hashmap
        Map<Integer, Integer> shuffleStrategyAwardSearchRateMap = new HashMap<>(strategyAwardSearchRateTables.size());
        for (int i = 0; i < strategyAwardSearchRateTables.size(); i++) {
            shuffleStrategyAwardSearchRateMap.put(i, strategyAwardSearchRateTables.get(i));
        }

        //7.存储到redis中
        strategyRepository.storeStrategyAwardSearchRateTables(key, strategyAwardSearchRateTables.size(), shuffleStrategyAwardSearchRateMap);
    }

    @Override
    public Integer getRandomAwardId(Long strategyId) {
        int rateRange = strategyRepository.getRateRange(strategyId);
        return strategyRepository.getStrategyAwardAssemble(String.valueOf(strategyId),new SecureRandom().nextInt(rateRange));
    }

    @Override
    public Integer getRandomAwardId(Long strategyId,String ruleWeightValue) {
        String key = String.valueOf(strategyId).concat("_").concat(ruleWeightValue);
        int rateRange = strategyRepository.getRateRange(key);
        return strategyRepository.getStrategyAwardAssemble(key,new SecureRandom().nextInt(rateRange));
    }

    /**
     * 根据策略ID和奖品ID，扣减奖品缓存库存
     *
     * @param strategyId 策略ID
     * @param awardId    奖品ID
     * @return 扣减结果
     */
    @Override
    public Boolean subtractionAwardStock(Long strategyId, Integer awardId) {
        String cacheKey = STRATEGY_AWARD_STOCK_KEY + strategyId + Delimiter.UNDERLINE + awardId;
       return strategyRepository.subtractionAwardStock(cacheKey);
    }

    private void cacheStrategyAwardCount(Long strategyId, Integer awardId,Integer awardCountSurplus) {
        String cacheKey = STRATEGY_AWARD_STOCK_KEY + strategyId +Delimiter.UNDERLINE + awardId;
        strategyRepository.storeAwardStockCount(cacheKey,awardCountSurplus.longValue());
    }
}
